<?php

namespace App\Criteria;
use Illuminate\Database\Eloquent\Builder;
use Prettus\Repository\Contracts\CriteriaInterface;
use Prettus\Repository\Contracts\RepositoryInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class PostSearchCriteriaCriteria
 * @package namespace App\Criteria;
 */
class PostSearchCriteria implements CriteriaInterface
{

    /**
     * @var \Illuminate\Http\Request
     */
    protected $request;

    /**
     * PostSearchCriteriaCriteria constructor.
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * Apply criteria in query repository
     *
     * @param Builder $model
     * @param RepositoryInterface $repository
     * @return mixed
     */
    public function apply($model, RepositoryInterface $repository)
    {
        $title = $this->request->get('title', null);
        $published = $this->request->get('published', null);
        $title && $model=$model->where('title', 'like', '%'.$title.'%');
        $published && $model=$model->where('published', '=', ''.$published);
        return $model;
    }
}
